package com.yesjpt.serv.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.yesjpt.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson2.JSONObject;
import com.yesjpt.dao.NoticeDao;
import com.yesjpt.domain.Notice;
import com.yesjpt.domain.Notice.Status;
import com.yesjpt.serv.NoticeServ;
import com.yesjpt.util.JsonUtil;
import com.yesjpt.util.L;

@Service
@Transactional
public class NoticeServImpl extends BaseServImpl implements NoticeServ {
	
	@Autowired private NoticeDao dao;

	@Override
	@Transactional
	public JSONObject add(Notice vo) {
		L.i(new Throwable().getStackTrace()[0]);
		JSONObject o = JsonUtil.succ("新增操作成功！");
		try {
			vo.setId(StringUtil.genGuid());
			vo.setCreatorId("admin");
			vo.setUpdateTime(new Date());
		} catch (Exception e) {
			e.printStackTrace();
			o = JsonUtil.fail("新增操作异常", "请检查ID是否冲突！");
		}
		return o;
	}

	@Override
	public JSONObject update(Notice vo) {
		L.i(new Throwable().getStackTrace()[0]);
		Notice no = dao.findById(vo.getId());
		if (no.getStatus() == Status.PUBLISH) {
			return JsonUtil.fail("更新操作失败", "发布状态的不能修改");
		}
		JSONObject o = JsonUtil.succ("成功修改好了！");
		try {
			int i = dao.update(vo);
			if(i == 0) {
				return JsonUtil.fail("保存操作失败", "受影响的行数为0");
			}
		} catch (Exception e) {
			e.printStackTrace();
			o = JsonUtil.fail("保存操作异常", "可能的原因是输入的标题为空");
		}
		return o;
	}

	@Override
	@Transactional
	public JSONObject delete(String id) {
		L.i(new Throwable().getStackTrace()[0]);
		Notice vo = dao.findById(id);
		if(vo.getStatus() == Status.PUBLISH) {
			return JsonUtil.fail("删除操作失败！", "发布的状态不能删除");
		}
		dao.delete(id);
		return JsonUtil.succ("删除操作成功！");
	}

	@Override
	public Notice findById(String id) {
		L.i(new Throwable().getStackTrace()[0]);
		return dao.findById(id);
	}
	
	@Override
	public List<Notice> listByParams(Map<String, Object> params){
		L.i(new Throwable().getStackTrace()[0]);
		return dao.listByParams(params);
	}

}
